package data.content;

import java.io.IOException;

import data.content.visitor.ContentVisitor;

import network.e2e.FrameReader;
import network.e2e.FrameWriter;

/**
 * Immutable class that represents a data of a form single string with specific limit
 */

public class ContentSentence implements Content {
  
  /**
   * Maximum length of the content of a ContentSentence
   */
  public final static int CONTENT_SENTENCE_MAX_LENGTH = 500;
  
  public final String sentence_;
  
  /**
   * Rep invariant
   */
  private void checkRep() {
    assert (sentence_ != null) :
      "ContentSentence: sentence_ must not be null";
    assert (sentence_.length() <= CONTENT_SENTENCE_MAX_LENGTH) :
      "ContentSentence: sentence_'s length must not exceed " +
      CONTENT_SENTENCE_MAX_LENGTH;
  }
  
  /**
   * Creates a new sentence
   * @requires sentence not null
   * @param sentence  Content of this entity
   * @complexity A(1)
   */
  public ContentSentence(String sentence) {
    assert sentence != null;
    
    sentence_ = sentence;
    checkRep();
  }
  
  /**
   * Decodes a new sentence from the net
   * @requires reader not null
   * @param reader the net
   * @throws IOException 
   */
  public ContentSentence(FrameReader reader) throws IOException {
    assert reader != null;
    
    String str = reader.readString();
    assert (str != null);
    sentence_ = str;
    
    checkRep();
  }
  
  /**
   * Retrieves the content of this entity
   * @return the sentence represented by this object
   * @complexity A(1)
   */
  public String getSentence() {
    return sentence_;
  }
  
  @Override
  public String toString() {
    return this.getSentence();
  }
  
  /**
   * Equal iff the strings represented are equal
   * @param  obj the object to be compared with
   * @return true iff the strings represented are equal
   * @complexity A(1)
   */
  @Override
  public boolean equals(Object obj) {
    if (!(obj instanceof ContentSentence)) return false;
    ContentSentence that = (ContentSentence)obj;
    return this.getSentence().equals(that.getSentence());
  }
  
  public <T> T accept(ContentVisitor<T> visitor) {
    assert visitor != null;
    return visitor.visit(this);
  }

  public void send(FrameWriter writer) throws IOException {
    assert writer != null;
    writer.writeString(this.getSentence());
  }
  
}
